import React, { forwardRef, useState, useEffect } from 'react';
import { Form, Modal, Select, ModalFuncProps, Spin } from 'antd';
import { getMessage } from '@inbiz/react';
import service from '../service';
import './style.less';

const PositionSelector: React.ForwardRefRenderFunction<
  any,
  ModalFuncProps & {
    users: any;
  }
> = (props: any, ref) => {
  const { users, onOk, onCancel, visible } = props;
  const [form] = Form.useForm();
  const [pageLoading, setPageLoading] = useState(false);
  const [formData, setFormData] = useState<any[]>([]);

  useEffect(() => {
    setPageLoading(true);
    service
      .getUserInfoByUserId({ userIds: users?.map((item: any) => item?.id)?.join(',') })
      .then((res: any) => {
        let _formDataObject = {};
        res?.data?.map((item: any) => {
          let _userId = item?.split(',')?.[0];
          _formDataObject[_userId] = [];
        });
        res?.data?.map((item: any) => {
          let _userId = item?.split(',')?.[0];
          let _postionArray = item
            ?.split(',')?.[1]
            ?.split('\\')
            ?.filter((item1: any) => item1);
          let _positionPath = _postionArray[_postionArray?.length - 1];
          if (_formDataObject[_userId]) {
            _formDataObject[_userId]?.push(_positionPath);
          }
        });
        let _formData = [];
        for (const k in _formDataObject) {
          let _label = users?.find((item: any) => item?.id == k)?.name;
          _formData?.push({
            label: _label,
            options: _formDataObject[k]?.map((item3: any) => {
              return {
                value: item3,
                label: item3,
              };
            }),
          });
        }
        setFormData(_formData);
        setPageLoading(false);
      })
      .catch((error: any) => {
        setPageLoading(false);
      });
  }, [users]);

  const formProps = {
    form,
    name: 'positionSelector',
    colon: true,
    labelCol: { span: 5 },
    labelAlign: 'left',
    wrapperCol: { span: 18 },
  };

  return (
    <Modal
      onOk={(e) => {
        onOk?.({
          form,
        });
      }}
      onCancel={(e) => {
        form.resetFields();
        onCancel?.(e);
      }}
      visible={visible}
      title={getMessage('MemberSelect.lang.positionSelect')}
      wrapClassName="memberSelector-positionSelector-wrapper"
      maskStyle={{ zIndex: 1051 }}
      okText={getMessage('MemberSelect.lang.action.ok')}
      cancelText={getMessage('MemberSelect.lang.action.cancel')}
    >
      <div className="memberSelector-positionSelector" style={{ height: users?.length * 56 }}>
        <Spin spinning={pageLoading}>
          <Form {...formProps}>
            {formData?.length > 0 &&
              formData?.map((item: any, index: number) => {
                return (
                  <Form.Item
                    label={item?.label}
                    name={users[index]?.key}
                    key={users[index]?.key}
                    rules={[
                      {
                        required: true,
                        message: getMessage('MemberSelect.lang.plzSelectPosition'),
                      },
                    ]}
                    initialValue={item?.options?.[0]?.value}
                  >
                    <Select
                      options={item?.options}
                      getPopupContainer={() => document.body}
                      dropdownClassName="memberSelector-positionSelector-dropdown-wrapper"
                    />
                  </Form.Item>
                );
              })}
          </Form>
        </Spin>
      </div>
    </Modal>
  );
};

export default forwardRef(PositionSelector);
